import config from '../static/config.json' with { type: 'json' }
import { useCrypto } from '../../package-A/hooks/useCrypto.js'
export const request = (api, data, option, loadingProperty) => {
	const requestJson = {...config}
	const isCustomUrl = option?.isCustomUrl
	const isReturnRes = option?.isReturnRes
	let requestHeader = {}
	return new Promise((resolve, reject )=>{
		if (option?.isCrypto) {
			const {encoded, getGlobalHeaders} = useCrypto()
			for(let key in data) {
				data[key] = encoded(data[key])
			}
			requestHeader = getGlobalHeaders(api, data)
		} else {
			if(requestJson.APP_ID) {
				requestHeader['x-app-id'] = requestJson.APP_ID
				requestHeader['x-tenant-id'] = requestJson.APP_ID
			}
			if(option?.header) requestHeader = {...requestHeader , ...option?.header}
			// if(uni.getStorageSync('token')) header['authorization'] = `Bearer ${uni.getStorageSync('token')}`
		}
		console.log(requestHeader,'---header---')
		// 请求接口添加
		let requestUrl = `${requestJson.BASE_URL}/${requestJson.APP_ID}${api}`
		if(isCustomUrl) requestUrl = api
		console.log(requestUrl,'---requestUrl---')
		// 请求设置
		const requestData = {
			url: requestUrl,
			data,
			timeout: 1000 * 60 * 3,
			method: option?.method,
			header: requestHeader,
			success: (res) => {
				const code = res?.data?.code || ''
				const msg = res?.data?.message || ''
				if (code === 200) {
					resolve(isReturnRes ? res.data.data : res.data)
					return
				}
				// 接口没有权限
				if (['登录过期！','Not Authenticated'].includes(msg)) {
					// userStore.logout()
					// goto('/pages/login/index')
				}
				setTimeout(()=>{
					// uni.showToast({title: res.data.message || '请求失败！', icon: 'none',duration:2000,position:'center'})
				},30)
				reject()
			},
			fail: (err) => {
				setTimeout(()=>{
					// uni.showToast({title: err.errMsg || '请求失败！', icon: 'none'});
				},30)
				reject(err)
			},
			complete: () => {
				// uni.hideLoading();
			}
		}
		// 加载中
		if (loadingProperty?.isLoading) uni.showLoading({title: loadingProperty?.loadingTitle || '加载中...'})
		// 发送请求
		uni.request(requestData)
	})
}

export const uploadFile=(file, path, isShowLoad) =>{
	path = path ?? '/system/affix/upload'
	isShowLoad = isShowLoad ?? true
	if (isShowLoad) {
		uni.showLoading({
			title: '上传中',
			mask: true
		});
	}
	return new Promise((resolve, reject) => {
		uni.uploadFile({
			url: `${config.BASE_URL}` + path, //仅为示例，非真实的接口地址
			filePath: file,
			name: 'files',
			header:{
				'x-app-id': `${config.APP_ID}`,
				'x-tenant-id': `${config.APP_ID}`,
				'authorization': `Bearer ${uni.getStorageSync('token')}`
			},
			success: (res) => {
				const {code,data} = JSON.parse(res.data)
				if(code !== 200) {
					reject()
					return
				};
				resolve({data, code})
			},
			fail:(err) => {
				uni.showToast({
					title: '上传失败',
					mask:true,
					duration: 2000,
					icon:"none"
				});
				reject(err)
			},
			complete: () => {
				if (isShowLoad) {
					uni.hideLoading()
				}
			}
		});
	})
}


export const api={};
['get','post','put','delete'].forEach((method)=>{
	api[method] =(api,data,option,loadingProperty)=>{
		option = option || {}
		option.header={'Content-Type':!option.isJson ? 'application/json':'application/x-www-form-urlencoded',
			 ...(option?.header || {})} //默认json格式
		option.method = method
		option.isCustomUrl = option.isCustomUrl ?? false // 对url进行自定义处理，默认true但用户可覆盖
		option.isReturnRes = option.isReturnRes ?? false // 对返回值是否拆一层data包裹，false则不拆
		return request(api, data, option, loadingProperty)
	}
})

